<?php

use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;

$appID = '380285178794317';
$appSecret = '139ea05c613089aa6994699517b936b9';
$redirect_uri = $home_url;
$permissions = array('public_profile');

FacebookSession::setDefaultApplication($appID,$appSecret);
$helper = new FacebookRedirectLoginHelper($redirect_uri);

if(isset($_SESSION) && isset($_SESSION['fb_token'])){
	$session = new FacebookSession($_SESSION['fb_token']);
	
	try{
		if(!$session->validate()){
			$session = null;
		}
	}catch(Exception $e){
		$session = null;
	}
}else{
	try{
		$session = $helper->getSessionFromRedirect();
	}catch(FacebookRequestException $e){
		// When Facebook returns an error
	}catch(Exception $e){
		// When validation fails or other local issues
		echo $e->message();
	}
}
// Check if a session exists
if(isset($session)){
	try {
		$request = new FacebookRequest($session, 'GET', '/me');
		$response = $request->execute();
		$me = $response->getGraphObject(GraphUser::className());
		$fb_name = $me->getName();
	}catch (FacebookRequestException $e){
		// The Graph API returned an error
	}catch(Exception $e){
		// Some other error occurred
	}
	// Save the session
	$_SESSION['fb_token'] = $session->getToken();
	// Create session using saved token or the new one we generated at login
	$session = new FacebookSession($session->getToken());
	// Create the logout URL (logout page should destroy the session)
	//$logoutURL = $helper->getLogoutUrl( $session, 'http://yourdomain.com/logout' );
	//echo '<a href="' . $logoutURL . '">Log out</a>';
}else{
	// No session
	// Get login URL
	//$loginUrl = $helper->getLoginUrl();
	//echo '<a href="' . $loginUrl . '">Log in</a>';
}